<?php

declare(strict_types=1);
/**
 * This file is part of qbhy/hyperf-auth.
 *
 * @link     https://github.com/qbhy/hyperf-auth
 * @document https://github.com/qbhy/hyperf-auth/blob/master/README.md
 * @contact  qbhy0715@qq.com
 * @license  https://github.com/qbhy/hyperf-auth/blob/master/LICENSE
 */
namespace App\Middleware;

use App\Common\Http\Response;
use App\Constants\ErrorCode;
use App\Service\AppUserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use phpDocumentor\Reflection\Types\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\Authenticatable;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;

/**
 * Class AuthMiddleware.
 */
class Auth implements MiddlewareInterface
{
    protected array $guards = [null];

    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    /**
     * @var ContainerInterface
     */
    protected $container;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->appUserService = $container->get(AppUserService::class);
        $this->response = $container->get(Response::class);
        $this->request = $container->get(RequestInterface::class);

    }

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
//            $getHeaders = $request->getHeaders();
//            var_dump($getHeaders);
        foreach ($this->guards as $name) {
            $guard = $this->auth->guard($name);
            var_dump($request->getHeaders());
            var_dump($guard->id());
            if($guard->check()==false){
                return $this->response->error(ErrorCode::UNAUTHORIZED, "未登录或已过期");
            }else{
                if (! $guard->user() instanceof Authenticatable) {
                    throw new UnauthorizedException("Without authorization from {$guard->getName()} guard", $guard);
                }else{
                    $guard->id();
//                        var_dump( $guard->id());
                    \Hyperf\WebSocketServer\Context::set('link_id',$guard->id());
                }
            }
        }
        return $handler->handle($request);
    }
}
